from flask import Blueprint, request, current_app
from app.utils.response_util import ResponseUtil
from config.node_config import NODE_TYPES

bp = Blueprint('node', __name__, url_prefix='/api/nodes')

@bp.route('/<node_type>', methods=['GET'])
def get_nodes(node_type):
    """获取指定类型的所有节点"""
    try:
        node_service = current_app.node_service
        nodes = node_service.get_nodes(node_type)
        return ResponseUtil.success(data={'nodes': nodes})
    except Exception as e:
        return ResponseUtil.error(str(e))

@bp.route('/<node_type>', methods=['POST'])
def create_node(node_type):
    """创建新节点"""
    try:
        data = request.get_json()
        node_service = current_app.node_service
        
        if node_type == 'CulturalItem':
            result = node_service.create_cultural_item(data)
        else:
            result = node_service.create_node(node_type, data)
            
        return ResponseUtil.success(data={'node': result})
    except Exception as e:
        return ResponseUtil.error(str(e))

@bp.route('/<node_type>/<node_id>', methods=['PUT'])
def update_node(node_type, node_id):
    """更新节点"""
    try:
        data = request.get_json()
        node_service = current_app.node_service
        result = node_service.update_node(node_type, node_id, data)
        return ResponseUtil.success(data={'node': result})
    except Exception as e:
        return ResponseUtil.error(str(e))

@bp.route('/<node_type>/<node_id>', methods=['DELETE'])
def delete_node(node_type, node_id):
    """删除节点"""
    try:
        node_service = current_app.node_service
        node_service.delete_node(node_type, node_id)
        return ResponseUtil.success(message="节点删除成功")
    except Exception as e:
        return ResponseUtil.error(str(e))

@bp.route('/types', methods=['GET'])
def get_node_types():
    """获取所有节点类型及其中文标签"""
    types = {key: value["label"] for key, value in NODE_TYPES.items()}
    return ResponseUtil.success(data=types)